package com.jscloud.bigdata.flink.demo1;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class WordCountStreamJava {
        public static void main(String[] args) throws Exception {
                //流式数据处理编程入口类 StreamExecutionEnvironment
                StreamExecutionEnvironment evn = StreamExecutionEnvironment.getExecutionEnvironment();

                //获取 socket 里的数据
                DataStreamSource<String> sourceDataStream = evn.socketTextStream("bigdata01", 9999);

                //获取数据
                SingleOutputStreamOperator<String> eachWord = sourceDataStream.flatMap(new FlatMapFunction<String, String>() {
                        @Override
                        public void flatMap(String value, Collector<String> out) throws Exception {
                                String[] eachWords = value.split(" ");
                                for (String eachWord : eachWords) {
                                        out.collect(eachWord);
                                }
                        }
                });

                SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = eachWord.map(new MapFunction<String, Tuple2<String, Integer>>() {
                        @Override
                        public Tuple2<String, Integer> map(String value) throws Exception {
                                Tuple2<String, Integer> tuple2 = new Tuple2<>();
                                tuple2.setFields(value, 1);
                                return tuple2;
                        }
                });
                //执行程序
                SingleOutputStreamOperator<Tuple2<String, Integer>> resultSum = wordAndOne.keyBy(0).sum(1);
                resultSum.print();

                evn.execute();
        }

}
